package com.mjk.common.web.getway.restful.filter;

import com.mjk.common.web.getway.utils.RequstParaseUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.*;

public class RestParamsFilter extends OncePerRequestFilter {
	protected void doFilterInternal(HttpServletRequest request,
									HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		ModifyParametersWrapper mParametersWrapper = new ModifyParametersWrapper(
				request);
		filterChain.doFilter(mParametersWrapper, response);
	}

	private class ModifyParametersWrapper extends HttpServletRequestWrapper {
		private final Map<String, Object> customHeaders;

		public ModifyParametersWrapper(HttpServletRequest request) {
			super(request);
			Map<String, Object> map = RequstParaseUtils
					.getMapFromRequest(request);

			this.customHeaders = new HashMap<>(map);
		}
		@Override
		public Object getAttribute(String name) {
			if (this.customHeaders.get(name) != null) {
				return this.customHeaders.get(name);
			}
			return super.getAttribute(name);
		}

		@SuppressWarnings("unused")
		public void putHeader(String name, String value) {
			this.customHeaders.put(name, value);
		}
		@Override
		public String getHeader(String name) {
			String headerValue = (String) this.customHeaders.get(name);
			if (headerValue != null) {
				return headerValue;
			}
			return ((HttpServletRequest) getRequest()).getHeader(name);
		}
		@Override
		public Enumeration<String> getHeaderNames() {
			Set<String> set = new HashSet<>(this.customHeaders.keySet());
			@SuppressWarnings("unchecked")
			Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
			while (e.hasMoreElements()) {
				String n =  e.nextElement();
				set.add(n);
			}
			return Collections.enumeration(set);
		}
	}
}